

import time
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
#导入Django自带的哈希加密解密
from django.contrib.auth.hashers import make_password, check_password
#导入随机模块用来生成随机账号
import random
#导入models中的类对数据库进行操作
import requests
from Lost_Found import  models


'''
@def Random_password,registers,login
@function 注册登录
@author yinzhecheng
@date 2022/2/14
'''

#生成一个随机ID，账号由两个大写字母两个小写字母和四个数字组成
def Random_password():
    String = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    string = ['a','b','c','d','e','f','g','h','i','j','k','l','n','n','o','p','q','r','s','t','u','v','w','x','y','z']
    num = ['0','1','2','3','4','5','6','7','8','9']
    user_id = ''
    # while(1):
    for item in range(2):
        number = random.randint(0,25)
        user_id = user_id + String[number]

    for item in range(2):
        number = random.randint(0,25)
        user_id = user_id + string[number]

    for item in range(4):
        number = random.randint(0,9)
        user_id = user_id + num[number]
    return user_id

# qq_code = ''
#
# def send_qq_code(request):
#     """
#     发送邮箱验证码
#     :param to_mail: 发到这个邮箱
#     :return: 成功：0 失败 -1
#     """
#     # 生成邮箱验证码
#     qq_code = '%04d' % random.randint(0, 9999)
#     email = '2318247512@qq.com'
#     email_title = '邮箱激活'
#     email_body = "您的邮箱注册验证码为:{0}, 该验证码有效时间为两分钟,请及时进行验证。".format(qq_code)
#     send_status = send_mail(subject=email_title, message=email_body, from_email=EMAIL_HOST_USER, recipient_list=[email])
#     return JsonResponse({'code':qq_code})


#注册账号
def registers(request):

    if request.method != 'POST':   #如果不是POST，抛出表单，否则提交表单
        return render(request,'login.html')
    elif request.POST.get("submit") == "get_code" :
        name = request.POST.get("name")
        password = request.POST.get("password")
        password_ag = request.POST.get("password_ag")
        tel = request.POST.get("tel")
        tel_list = models.Users.objects.filter(user_tel=tel)
        if tel_list :
            error1 = ".号码已注册"
            return render(request, 'login.html', {'name': name, 'password': password, 'password_ag': password_ag,
                                                  "error1": error1})
        if request.POST.get("tel") == "" or len(request.POST.get("tel")) != 11:
            error1 = ".请填写正确号码"
            return render(request, 'login.html',{'name': name, 'password': password, 'password_ag': password_ag,
                                                     "error1":error1})
        tel_code = '%04d' % random.randint(0, 9999)
        request.session["code"] = tel_code
        header = {
            "Authorization": "APPCODE de9c1b122840409cb40daa14c385d084",
        }
        body = {
            "content": f'code:{ tel_code }',
            "phone_number": f'{tel}',
            "template_id": "TPL_0000",
        }
        url = 'https://dfsns.market.alicloudapi.com/data/send_sms'
        response = requests.post(url=url, data=body, headers=header)
        print(tel_code)
        return render(request,'login.html',{'name':name,'password':password,'password_ag':password_ag,'tel':tel})

    else:   #提交表单并验证输入的信息
        name = request.POST.get("name")
        password = request.POST.get("password")
        password_ag = request.POST.get("password_ag")
        tel = request.POST.get("tel")
        code = request.POST.get("code")
        if not name or not password or not password_ag or not tel:
            error1 = '.请填写完整信息'
            return render(request, 'login.html',
                          { 'error1':error1, 'name': name, 'password': password, 'password_ag': password_ag,
                           'tel':tel, 'code': code})

        id = Random_password()
        #filter返回一个列表，匹配数据库中的user_name是否有name，下同
        user_list = models.Users.objects.filter(user_name=name)
        #用来判断该账号是否唯一，如若存在则进行提示
        if user_list:
            error1 = '.用户名已存在'
            return  render(request,'login.html',{'error1':error1,'name':name,'password':password,'password_ag':
                password_ag,'tel':tel,'code':code})
        #用来判断两次密码是否一致，如若不一致则做出提示
        if password != password_ag:
            error1 = '.两次密码不一致'
            return  render(request,'login.html',{'error1':error1,"name":name,'password':password,'password_ag':
                password_ag,'tel':tel,'code':code})

        #用来判断验证码是否正确
        if code != request.session['code'] :
            error1 = '.验证码有误'
            return  render(request,'login.html',{'error1':error1,"name":name,'password':password,
                                                     'password_ag':password_ag,'tel':tel,'code':code})
        else:
            user_list1 = models.Users.objects.filter(user_id=id)
            #用来判断随机生成的ID是否唯一，如若存在则重新生成一个直到生成的ID为唯一的
            while(1):
                if user_list1:
                    id = Random_password()
                    user_list1 = models.Users.objects.filter(user_id=id)
                else:break
            xiha_password = make_password(password,None,'pbkdf2_sha256')
            user = models.Users.objects.create(user_name=name, user_password=xiha_password, user_id=id, user_tel=tel)
            user.save()
    return render(request,'login.html')

#账号登录
def login(request):
    if request.method != 'POST':
        return render(request,'login.html')
    else:

        tel = request.POST.get("tel")
        password = request.POST.get("password")
        #判断用户是否存在，如果不存在静默失败，提示用户
        try:
            user_tel = models.Users.objects.get(user_tel=tel)
        except:
            error = '.用户不存在'
            return render(request,'login.html',{'error':error})
        Info_user = models.Users.objects.get(user_tel = tel)
        XIHA_password = Info_user.__dict__['user_password']
        #通过check_password检测密码是否正确
        if check_password(password,XIHA_password):
            user_id = models.Users.objects.get(user_tel=tel).user_id
            request.session["user_id"] = user_id
            request.session["is_login"] = True
            return redirect('start_views')
        else:
            #如果密码错误，刷新页面时用户名仍然存在
            old_tel = tel
            error = '.密码错误'
            return render(request,'login.html',{'error':error,'old_tel':old_tel})

#忘记密码
def lose_password(request):
    if request.method != "POST":
        return render(request,"lose_password.html")
    elif request.POST.get("submit") == "get_code":
        tel = request.POST.get("tel")
        password = request.POST.get("password")
        password_ag = request.POST.get("password_ag")
        if request.POST.get("tel") == "" or len(request.POST.get("tel")) != 11:
            error = ".请填写正确号码"
            return render(request, 'lose_password.html', {'tel': tel, 'password': password, 'password_ag': password_ag,
                                                      "error": error})
        tel_code = '%04d' % random.randint(0, 9999)
        request.session["code"] = tel_code
        header = {
            "Authorization": "APPCODE de9c1b122840409cb40daa14c385d084",
        }
        body = {
            "content": f'code:{tel_code}',
            "phone_number": f'{tel}',
            "template_id": "TPL_0000",
        }
        url = 'https://dfsns.market.alicloudapi.com/data/send_sms'
        response = requests.post(url=url, data=body, headers=header)
        return render(request,'lose_password.html',{'tel':tel,'password':password,'password_ag':password_ag})
    else:
        tel = request.POST.get("tel")
        password = request.POST.get("password")
        password_ag = request.POST.get("password_ag")
        code = request.POST.get("code")
        if not tel or not password or not password_ag or not code:
            error = '.请填写完整信息'
            return render(request, 'lose_password.html',
                          { 'error':error, 'tel':tel , 'password': password, 'password_ag': password_ag,
                            'code': code})
        user_tel = models.Users.objects.filter(user_tel=tel)
        if not user_tel:
            tel_error = '.账号不存在'
            return  render(request,'lose_password.html',{'tel_error ':tel_error ,'tel':tel,'password':password,'password_ag'
            :password_ag,'code':code})
        #用来判断两次密码是否一致，如若不一致则做出提示
        if password != password_ag:
            error = '两次密码不一致'
            return  render(request,'lose_password.html',{'error':error,'password':password,'password_ag':password_ag,'tel':
                tel,'code':code})

        #用来判断验证码是否正确
        if code != request.session['code'] :
            error = '.验证码有误!'
            return  render(request,'lose_password.html',{'error':error,'password':password,'password_ag':
                password_ag,'tel':tel,'code':code})
        else:
            xiha_password = make_password(password, None, 'pbkdf2_sha256')
            models.Users.objects.filter(user_tel=tel).update(user_password=xiha_password)

            return render(request,'login.html')

#招领物品详情页面
def second_views_details(request):
    id = request.GET.getlist('id')
    list1 = list(map(str, id))
    id1 = int(list1[0])
    ob_info = models.Recruitment.objects.filter(id=id1)
    information = ob_info.first()
    return render(request,'second_views_details.html',{'data':information})

#寻物物品详情页面
def start_views_details(request):
    id = request.GET.getlist('id')
    list1 = list(map(str, id))
    id1 = int(list1[0])
    ob_info = models.Object_hunting.objects.filter(id=id1)
    information = ob_info.first()
    return render(request,'start_views_details.html',{'data':information})

def publish(request):
    if not 'user_id' in request.session:
        return redirect("/login/")
    if request.method == 'GET':
       return render(request, 'publish.html')
    else:
        release_type = request.POST['release_type']
        name = request.POST['name']
        classification = request.POST['classification']
        detail = request.POST['detail']
        date = request.POST['date']
        place = request.POST['place']
        contact_details = request.POST['contact']
        user_id = 1
        file_obj = request.FILES.get('img1')
        # print(username,password,phone,e_mail)
        file_name = 'img/' + str(user_id) + '_' + str(int(time.time())) + '.' + file_obj.name.split('.')[-1]
        # if file_obj.type.split('.')[-1] not in ['jpeg', 'jpg', 'png']:
        #     return HttpResponse('输入文件有误')
        if release_type == '寻物':
            try:
                hunting = models.Object_hunting()
                hunting.o_name = name
                hunting.o_classification = classification
                hunting.o_detail = detail
                hunting.o_date = date
                hunting.o_place = place
                hunting.o_contact_details = contact_details
                hunting.users_id = user_id
                hunting.o_picture = file_name
                hunting.save()
                f = open(f'media/{file_name}', mode='wb')
                for chunk in file_obj.chunks():
                    f.write(chunk)
                f.close()
            except Exception as e:
                print(e)
            return redirect('start_views')
        if release_type == '招领':
            try:
                recruitment = models.Recruitment()
                recruitment.r_name = name
                recruitment.r_classification = classification
                recruitment.r_detail = detail
                recruitment.r_date = date
                recruitment.r_place = place
                recruitment.r_contact_details = contact_details
                recruitment.users_id = user_id
                recruitment.r_picture = file_name
                recruitment.save()
                f = open(f'media/{file_name}', mode='wb')
                for chunk in file_obj.chunks():
                    f.write(chunk)
                f.close()
            except Exception as e:
                print(e)
            return redirect('second_views/')

#寻物的初始化搜索结果
def start_views(requests):
    count = models.Object_hunting.objects.count()#数据库中总数
    informations=models.Object_hunting.objects.order_by('-o_publish_time')[0:count]#随机打散数据排序，取出数据
    return render(requests,'start_views.html',locals())
    # return HttpResponse('ok')

#招领的初始化搜索结果
def second_views(requests):
    count = models.Recruitment.objects.count()#数据库中总数
    print(count)
    informations=models.Recruitment.objects.order_by('-r_publish_time')[0:count]#随机打散数据排序，取出所有数据库数据
    for information in informations:#令每个数据独立出来
        print('标题:',information.r_name,'发布日期:',information.r_publish_time)
    return render(requests,'second_views.html',locals())

#用户注销
def login_out(request):
    try:
        del request.session["user_id"]
    except:
        pass
    try:
        del request.session["is_login"]
    except:
        pass
    request.session.clear()
    request.session.flush()
    return redirect('start_views')

#用户中心
def per_center(request):
    user_id = request.session['user_id']
    user = models.Users.objects.filter(user_id=user_id).first()
    o_objects = models.Object_hunting.objects.filter(users_id=user.id)
    r_objects = models.Recruitment.objects.filter(users_id=user.id)
    return render(request,'per_center.html',{'user':user,'o_objects':o_objects,'r_objects':r_objects})

#其它
def about(request):
    return render(request,'about.html')

#寻物物品分类筛选
def search_classification(request):
    class1 = request.GET.getlist('classification')
    results = models.Object_hunting.objects.filter(o_classification=class1[0]).order_by('-o_publish_time')
    return render(request,'start_views.html',{'informations':results})

#寻物时间筛选
def search_start_time(request):
    start_time = request.POST.get('before_time')
    end_time = request.POST.get('late_time')
    result2 = models.Object_hunting.objects.filter(Q(o_date__gte=start_time) & Q(o_date__lte=end_time))
    # results2 = models.Object_hunting.objects.filter(o_publish_time__range =(start_time,end_time)).order_by('-o_publish_time')
    return render(request,'start_views.html',{'informations':result2})

#关键字
def search_keyword(request):
    keyword = request.POST.get('key')
    results = models.Object_hunting.objects.filter(
        Q(o_name__icontains=keyword)|Q(o_detail__icontains=keyword)|Q(o_place__icontains=keyword)|Q(
            o_contact_details__icontains=keyword))
    return render(request,"start_views.html",{'informations':results})


#寻物物品分类筛选
def search_classification1(request):
    class1 = request.GET.getlist('classification')
    results = models.Recruitment.objects.filter(r_classification=class1[0]).order_by('-r_publish_time')
    return render(request,'second_views.html',{'informations':results})

#寻物时间筛选
def search_second_time1(request):
    start_time = request.POST.get('before_time')
    end_time = request.POST.get('late_time')
    result2 = models.Recruitment.objects.filter(Q(r_date__gte=start_time) & Q(r_date__lte=end_time))
    # results2 = models.Object_hunting.objects.filter(o_publish_time__range =(start_time,end_time)).order_by('-o_publish_time')
    return render(request,'second_views.html',{'informations':result2})

#关键字
def search_keyword1(request):
    keyword = request.POST.get('key')
    results = models.Recruitment.objects.filter(
        Q(r_name__icontains=keyword)|Q(r_detail__icontains=keyword)|Q(r_place__icontains=keyword)|Q(
            r_contact_details__icontains=keyword))
    return render(request,"second_views.html",{'informations':results})

